<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>websocket test</title>
    <style type="text/css">
        h3, h4 {
            text-align: center;
        }
    </style>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
    <script type="text/javascript">
        var wsUrl = "ws://localhost:7000/ws/asset";
        // var wsUrl = "ws://150.158.3.23/socket.io/?EIO=4&transport=websocket";
        var lockReconnect = false;  //避免ws重复连接
        var ws = null;          // 判断当前浏览器是否支持WebSocket
        createWebSocket(wsUrl);   //连接ws
        function createWebSocket(url) {
            try {
                if ('WebSocket' in window) {
                    ws = new WebSocket(url);
                }
                initEventHandle();
            } catch (e) {
                reconnect(url);
                console.log(e);
            }
        }

        function initEventHandle() {
            ws.onclose = function (e) {
                reconnect(wsUrl);
                console.log('websocket 关闭: ' + e.code + ' ' + e.reason + ' ' + e.wasClean+ new Date().toLocaleString());
            };
            ws.onerror = function () {
                reconnect(wsUrl);
                console.log("连接错误!");
            };
            ws.onopen = function () {
                heartCheck.reset().start();      //心跳检测重置
                console.log("连接成功!" + new Date().toLocaleString());
            };
            ws.onmessage = function (event) {    //如果获取到消息，心跳检测重置
                heartCheck.reset().start();      //拿到任何消息都说明当前连接是正常的
                let dataStr = event.data;
                console.log("收到消息啦:" + dataStr);
                document.getElementById("alab").innerText=dataStr;
                // if (dataStr != 'pong') {
                //     let data = JSON.parse(dataStr);
                //     console.log("llws收到消息啦2:" + data);
                // }
            };
        }

        // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            ws.close();
        }

        function reconnect(url) {
            if (lockReconnect) return;
            lockReconnect = true;
            setTimeout(function () {     //没连接上会一直重连，设置延迟避免请求过多
                createWebSocket(url);
                lockReconnect = false;
            }, 2000);
        }

        //心跳检测
        var heartCheck = {
            timeout: 3000,        //1秒发一次心跳
            severTimeout: 5000,  //服务端超时时间
            timeoutObj: null,
            serverTimeoutObj: null,
            reset: function () {
                clearTimeout(this.timeoutObj);
                clearTimeout(this.serverTimeoutObj);
                return this;
            },
            start: function () {
                var self = this;
                this.timeoutObj = setTimeout(function () {
                    //这里发送一个心跳，后端收到后，返回一个心跳消息，
                    //onmessage拿到返回的心跳就说明连接正常
                    ws.send("ping");
                    console.log("ping!")
                    self.serverTimeoutObj = setTimeout(function () {//如果超过一定时间还没重置，说明后端主动断开了
                        ws.close();     //如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
                    }, self.timeout)
                }, this.timeout)
            }
        }
        function sendMessage() {
            var json = $("#Json").val();
            //json = JSON.stringify(json);
            if (typeof (WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
            } else {
                console.log("您的浏览器支持WebSocket");
                console.log(json);
                //socket.send('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
                ws.send(json);
            }
        }
    </script>
</head>
<body>

<p>Json数据：
<div><textarea name="Json" id="Json" cols="150" rows="15"></textarea></div>
<input style="width:100px;height:50px;margin-left:200px" type="button" onclick="sendMessage()" value="发送消息"/>

<h3>WebSocket测试，在<span style="color:red">控制台</span>查看测试信息输出！</h3>
收到的信息 : <span style="color:red"><label id="alab"></label></span>
<br>调用<br>/api/ws/sendOne 给客户端单发信息
<br>调用<br>/api/ws/sendAll 给客户端群发信息
</body>
</html>